<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-button
        type="primary"
        class="buttom-si"
        @click="rolesdialogVisible = true"
        >添加角色</el-button
      >

      <el-table border style="width: 100%" :data="rolesform">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 使用作用域插槽来获取信息 -->
          <template slot-scope="scope">
            <!-- 栅格系统的布局组件 平分为24 -->
            <!-- 通过for循环动态获取一级权限 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="[
                'bdbottom',
                i1 === 0 ? 'bdtop' : '',
                'maring',
                'vcenter',
              ]"
            >
              <!-- 渲染一级权限   span让其占据5列 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightid(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightid(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightid(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="bianji(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="rolesshan(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限 -->
            <!-- (scope.row)供获取树形控件的三级节点 -->
            <el-button
              type="warning"
              icon="el-icon-star-off"
              size="mini"
              @click="showSetDiglog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="rolesdialogVisible"
      width="50%"
      @close="rolesdialog"
    >
      <el-form
        label-width="80px"
        :model="rolesadd"
        ref="rolesaddref"
        :rules="rolesaddrules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesadd.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesadd.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="xiudialogVisible"
      width="50%"
      @close="rolesdialogbian"
    >
      <el-form
        label-width="80PX"
        :data="rolesidform"
        ref="rolesidformref"
        :rules="rolesidrules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesidform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesidform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="xiudialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="xiugaitijiao">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配权限"
      :visible.sync="setRigDialogVisible"
      width="50%"
      @close="setRigtclosed"
    >
      <!-- 树状控件 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeref"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRigDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import uri from "../../config/uri";
export default {
  data() {
    return {
      // 角色列表的数据
      rolesform: [],
      // 添加弹框的显示
      rolesdialogVisible: false,
      rolesadd: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色的预验证规则
      rolesaddrules: {
        roleName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
      },
      // 编辑角色的预验证规则
      rolesidrules: {
        roleName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
      },
      //   编辑对话框的显示与否
      xiudialogVisible: false,
      //   使用id查询角色的数据
      rolesidform: [],
      // 分配对话框的弹出与否
      setRigDialogVisible: false,
      // 权限数据
      rightslist: [],
      // 树形控件的绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 树形控件的default-expanded-key默认选中的节点id值数组
      defkeys: [],
      // 当前即将分配权限的角色id
      roleId: "",
    };
  },
  created() {
    this.roleslist();
  },
  methods: {
    // 角色列表
    async roleslist() {
      const res = await this.$http.get(uri.getroles);
      // console.log(res);
      this.rolesform = res.data;
    },
    // 添加角色的提交按钮
    async addUsers() {
      const res = await this.$http.post(uri.postroles, this.rolesadd);
      // console.log(res);
      if (res.meta.status === 201) {
        this.$message.success(res.meta.msg);
        this.rolesdialogVisible = false;
        this.roleslist();
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    // 关闭添加对话框刷新其中的内容
    rolesdialog() {
      this.$refs.rolesaddref.resetFields();
    },
    // 删除角色
    async rolesshan(id) {
      const confirmRoles = await this.$confirm(
        "永久删除该角色，是否继续",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmRoles !== "confirm") {
        this.$message.info("已取消删除");
      } else {
        const res = await this.$http.delete(uri.deleteroles + "/" + id);
        //   console.log(res)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg);
          this.roleslist();
        } else {
          this.$message.error(res.meta.msg);
        }
      }
    },
    // 根据id获取角色信息
    async bianji(id) {
      this.xiudialogVisible = true;
      const res = await this.$http.get(uri.getrolesid + "/" + id);
      // console.log(res);
      if (res.meta.status === 200) {
        this.rolesidform = res.data;
      }
    },
    // 关闭编辑对话框刷新其中的内容
    rolesdialogbian() {
      this.$refs.rolesidformref.resetFields();
    },
    // 编辑完成提交
    async xiugaitijiao() {
      const res = await this.$http.put(
        uri.putrolesid + "/" + this.rolesidform.roleId,
        this.rolesidform
      );
      // console.log(res)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg);
        this.xiudialogVisible = false;
        this.roleslist();
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    // 点击图标根据对应的id删除权限
    // 参数1：是通过作用域插槽传递的用户信息
    // 参数2：是权限的id
    async removeRightid(role, rightid) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm(
        "将删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        this.$message.info("已取消删除");
      } else {
        const res = await this.$http.delete(
          uri.deleterolesid + "/" + role.id + "/rights/" + rightid
        );
        //  console.log(res)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg);
          // 从新赋值删除过的数据
          role.children = res.data;
        } else {
          this.$message.error(res.meta.msg);
        }
      }
    },
    // 分配权限的按钮
    // 参数1：是通过作用域插槽传递的用户信息
    async showSetDiglog(role) {
      //  在打开分配权限对话框是把id保存
      this.roleId = role.id;
      // 获取所有权限列表的接口
      const res = await this.$http.get(uri.getrightsid);
      console.log(res);
      if (res.meta.status === 200) {
        this.rightslist = res.data;
        // 递归获取三级节点的id,存入到数组defkeys中
        this.getLesafkeys(role, this.defkeys);
      } else {
        this.$message.error("获取权限数据失败");
      }
      
      this.setRigDialogVisible = true;
    },
    //定义一个函数 通过递归的形式，获取角色下所有的三级权限的id，并保存到defkeys数组中
    // 参数1：节点
    // 参数2：要保存的到的数组
    getLesafkeys(node, arr) {
      // 如果当前node节点不包含children属性，则是三级权限
      if (!node.children) {
        arr.push(node.id);
      } else {
        node.children.forEach((item) => this.getLesafkeys(item, arr));
      }
    },
    // 分配管理关闭清除其中数据
    setRigtclosed() {
      this.defkeys = [];
    },
    // 分配权限提交
    async allotRights() {
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys(),
      ];

      const idSetr = keys.join(",");
      // console.log(idSetr)
      const res = await this.$http.post(
        uri.postrolesrights + "/" + this.roleId + "/rights",
        { rids: idSetr }
      );
      // console.log(res)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg);
        this.setRigDialogVisible = false;
        this.roleslist();
      } else {
        this.$message.error(res.meta.msg);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.buttom-si {
  margin-bottom: 20px;
}
.maring {
  margin: 0 50px;
}
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
